package fr.insalyon.sims.broadcast.network;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * This class is a stream transmitter for TCP protocol.
 * 
 * @author GONZALEZ Silvia, GOTTERO Jeremie, SATTAYAKAWEE Nutchanat
 */
public class TCPStreamTransmitter extends BaseStreamTransmitter {
	// ------------------------------------------------------- CONSTANTS -- //
	// ------------------------------------------------------ ATTRIBUTES -- //
	/**
	 * address to be connected to get the data
	 */
	private InetAddress address;
	/**
	 * port number to be connected to get the data
	 */
	private int port;
	/**
	 * socket of the transmitter
	 */
	private Socket socket;
	/**
	 * output stream for sending data
	 */
	private DataOutputStream output;
	
	// ---------------------------------------------------- CONSTRUCTORS -- //
	/**
	 * Constructor
	 * 
	 * @param address ip address where the transmitter will connect to
	 * @param port port number where the transmitter will connect to
	 */
	public TCPStreamTransmitter(InetAddress address, int port)
			throws IOException {
		this.address = address;
		this.port = port;
	}
	
	// --------------------------------------------------------- METHODS -- //
	
	public void connect() throws IOException {
		this.socket = new Socket(address, port);
		this.output = new DataOutputStream(socket.getOutputStream());
	}
	
	public void disconnect() {
		try {
			output.close();
			socket.close();
		} catch (IOException e) {
			// Ignored
		}
	}
	
	// ------------------------------------------------- PRIVATE METHODS -- //
	
	protected void init() throws IOException {
		// No initialization job to do here
	}

	public void writeStream(byte[] data, int offset, int length) throws IOException {
		output.write(data, offset, length);
	}
	
	protected void cleanUp() throws IOException {
		// No clean up job to do here
	}
	
	// --------------------------------------------------- INNER CLASSES -- //
}
